// pages/address/address.js
const api =require("../../api/index")

Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressList: []
    },
    async removeAddress(e) {
        const id = e.currentTarget.dataset.id;
        await api.address.remove(id)
        this.obtainList()
    },
    async obtainList() {
        const userInfo = wx.getStorageSync('token')
        const addressList = await api.address.addressList(userInfo.id)
        this.setData({ addressList }) 
    },
    beginAdd() {
        wx.navigateTo({
            url: '/pages/address/edit/edit',
            events: {
                Ok: async (model) => {
                    await api.address.add(model)
                    this.obtainList()
                }
            }
        })
    },
    async beginUpdate(e) {
        const id = e.currentTarget.dataset.id;
        const target = await api.address.getModel(id)
        wx.navigateTo({
            url: '/pages/address/edit/edit',
            events: {
                Ok: async model => {
                    await api.address.update(model);
                    this.obtainList()
                }
            },
            success: res => {
                res.eventChannel.emit('beginUpdate',{...target});
            }
        })
    },
    async cartChangeAddress(e) {
        const id = e.currentTarget.dataset.id;
        wx.reLaunch({
          url: '/pages/cart/cart?cid=' + id,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        this.obtainList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})